/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package c1007i.ass.business;

import c1007i.ass.entities.Customer;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Monkey
 */
@ManagedBean
@RequestScoped
public class CustomerManagedBean {
    public Customer cus;

    public Customer getCus() {
        return cus;
    }

    public void setCus(Customer cus) {
        this.cus = cus;
    }
    
    /**
     * Creates a new instance of CustomerManagedBean
     */
    public CustomerManagedBean() {
        cus=new Customer();
    }
    
    public String checkLogin(){
        String email=cus.getEmail();
        String pass=cus.getPassword();
        if(email.equals("haimv.viss@gmail.com") && pass.equals("123456")){
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
            session.setAttribute("hello", email);
            return "home?faces-redirect=true";
        }
        return "";
    }
    
    public String logOut(){
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.invalidateSession();
        return "login?faces-redirect=true";
    }
    
    public String getAutoRedirect() throws IOException {

        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

        if (session.getAttribute("hello") == null && !req.getRequestURI().contains("/login.xhtml")) {
            FacesContext context = FacesContext.getCurrentInstance();

            String contextPath = context.getExternalContext().getRequestContextPath();
            ((HttpServletResponse) context.getExternalContext().getResponse()).sendRedirect(contextPath + "/faces/login.xhtml");
        }
        return "";
    }
}
